package com.yehaikeji.workflow.controller.management;

import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yehaikeji.workflow.bean.Excelthing;
import com.yehaikeji.workflow.bean.Model;
import com.yehaikeji.workflow.bean.SmsOperation;
import com.yehaikeji.workflow.bean.thing;
import com.yehaikeji.workflow.bean.user;
import com.yehaikeji.workflow.common.util.ExcelUtil;
import com.yehaikeji.workflow.controller.bean.ResultMessage;
import com.yehaikeji.workflow.controller.bean.resultlist;
import com.yehaikeji.workflow.service.ModelService;
import com.yehaikeji.workflow.service.SmsOperationService;
import com.yehaikeji.workflow.service.incidentService;
import com.yehaikeji.workflow.service.thingService;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Controller
@RequestMapping("thingManager")
public class thingController {

	@Autowired
	private ModelService modelService;
	@Autowired
	private thingService thingService;
	@Autowired
	private SmsOperationService smsOperationService;
	
	private String uploademun = "/resource/upload";
	
	@RequestMapping(value = "/manage")
	private String manageradmin(ModelMap map) {
		map.put("ismenu",0);
		List<Model> list = modelService.queryAllModel();
		map.put("model", list);
		return "index";
	}
	
	@RequestMapping(value = "/listhistory")
	private String historyjsp(String thingid,ModelMap map) {
		Map<String, Object> map2=thingService.getrecordlisthistory(thingid);
		map.put("thing", map2.get("thing"));
		map.put("list", map2.get("list"));
		return "history";
	}
	
	
	@RequestMapping(value = "excel")
	@ApiOperation(value = "下载excel", notes = "下载excel")
	public void excel(HttpServletResponse response,String ids,HttpServletRequest request) {
		try {
			List<Excelthing> things = thingService.selectDownloadPage(Arrays.asList(ids.split(",")));
			String realpath = request.getSession().getServletContext().getRealPath("")+uploademun;
			
		    HSSFWorkbook workbook = ExcelUtil.dataToExcel(things,realpath);
	        OutputStream os = response.getOutputStream();
	        String fileName = "事项列表" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".xls";
	        byte[] fileNameByte = fileName.getBytes("GBK");
	        String filename = new String(fileNameByte, "ISO8859-1");
	        response.setContentType("application/x-msdownload");
	        response.setHeader("Content-Disposition",
	                "attachment;filename=" + filename);
	        workbook.write(os);
	        os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Map<String,List<thing>> setList(List<thing> things){
		Map<String,List<thing>>  map = new HashMap<String, List<thing>>();
		if(!CollectionUtils.isEmpty(things)){
			for(thing thing : things){
				if(thing.getTypeid() == 1){
					
				}else if(thing.getTypeid() == 2){
					
				}else if(thing.getTypeid() == 3){
					
				}else if(thing.getTypeid()== 4){
					
				}
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/chatdetail")
	private String chatdetail(ModelMap map,@RequestParam String phone,@RequestParam String thingId) {
		List<SmsOperation> list = smsOperationService.getChatDetailByPhone(phone,thingId);
		map.put("data", list);
		return "chatdetail";
	}


	@RequestMapping(value = "sendSms", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "发送短信", notes = "发送短信")
	public ResultMessage sendSms(@RequestParam String thingId,@RequestParam String phone,@RequestParam String modelId,@RequestParam String content,HttpSession httpSession) {
		ResultMessage resultMessage = new ResultMessage();
		try {
			if(null == httpSession || null == httpSession.getAttribute("user")){
				throw new RuntimeException("当前用户没有登录");
			}
			SmsOperation smsOperation = new SmsOperation();
			smsOperation.setModelId(modelId);
			smsOperation.setThingId(thingId);
			smsOperation.setPhone(phone);
			smsOperation.setUserId(((user)httpSession.getAttribute("user")).getUserid());
			smsOperation.setType("1");
			smsOperation.setContent(content);
			resultMessage.setData(smsOperationService.addSmsOperation(smsOperation));
			resultMessage.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			resultMessage.setMessage(e.getMessage());
			resultMessage.setSuccess(false);
		}
		return resultMessage;
	}
	

	@RequestMapping(value = "inserthing", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加一个事务", notes = "typeid=1是代办，typeid=2代发，typeid=3是代收,typeid=4一体化救助平台")
	public ResultMessage inserthingandincident(thing thing,@ApiParam(value="交件时间")
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date createdatei,String sendname, String acceptname,
			@ApiParam(value="交件社区id")String unitida,@ApiParam(value="中转部门（接件部门）id")String unitidb,@ApiParam("办理单位id")String unitidc) {
		ResultMessage resultMessage = new ResultMessage();
		try {
			if(StringUtil.isEmpty(thing.getUserid())){
				throw new RuntimeException("userId不能为空");
			}
			if(thing.getTypeid() == null){
				throw new RuntimeException("Typeid不能为空");
			}
			if(createdatei == null){
				throw new RuntimeException("createdatei不能为空");
			}
//			if(StringUtil.isEmpty(sendname)){
//				throw new RuntimeException("sendname不能为空");
//			}
			if(StringUtil.isEmpty(thing.getName())){
				throw new RuntimeException("name不能为空");
			}
			if(thing.getNumber() == null){
				throw new RuntimeException("number不能为空");
			}
//			if(StringUtil.isEmpty(acceptname)){
//				throw new RuntimeException("acceptname不能为空");
//			}
			if(StringUtil.isEmpty(unitida)){
				throw new RuntimeException("unitida不能为空");
			}
			if(StringUtil.isEmpty(unitidb)){
				throw new RuntimeException("unitidb不能为空");
			}
			resultMessage.setData(thingService.inserthing(thing, createdatei, sendname, acceptname, unitida,unitidb,unitidc));
			resultMessage.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			resultMessage.setMessage(e.getMessage());
			resultMessage.setSuccess(false);
		}
		return resultMessage;
	}
	
	@RequestMapping(value = "inserthingok", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "添加一个事务,不签名", notes = "typeid=1是代办，typeid=2代发，typeid=3是代收,typeid=4一体化救助平台")
	public ResultMessage inserthingandincidentok(thing thing,@ApiParam(value="交件时间")
			@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date createdatei,String sendname, String acceptname,
			@ApiParam(value="交件社区id")String unitida,@ApiParam(value="中转部门（接件部门）id")String unitidb) {
		ResultMessage resultMessage = new ResultMessage();
		try {
			System.out.println(thing);
			if(StringUtil.isEmpty(thing.getUserid())){
				throw new RuntimeException("userId不能为空");
			}
			if(thing.getTypeid() == null){
				throw new RuntimeException("Typeid不能为空");
			}
			if(createdatei == null){
				throw new RuntimeException("createdatei不能为空");
			}
//			if(StringUtil.isEmpty(sendname)){
//				throw new RuntimeException("sendname不能为空");
//			}
			if(StringUtil.isEmpty(thing.getName())){
				throw new RuntimeException("name不能为空");
			}
			if(thing.getNumber() == null){
				throw new RuntimeException("number不能为空");
			}
//			if(StringUtil.isEmpty(acceptname)){
//				throw new RuntimeException("acceptname不能为空");
//			}
			if(StringUtil.isEmpty(unitida)){
				throw new RuntimeException("unitida不能为空");
			}
			if(StringUtil.isEmpty(unitidb)){
				throw new RuntimeException("unitidb不能为空");
			}
			resultMessage.setData(thingService.inserthingok(thing, createdatei, sendname, acceptname, unitida,unitidb));
			resultMessage.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			resultMessage.setMessage(e.getMessage());
			resultMessage.setSuccess(false);
		}
		return resultMessage;
	}

	@RequestMapping(value = "selectthingpagelist", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "事务列表")
	public resultlist selectthingpagelimit(@RequestParam Integer page, @RequestParam Integer limit, String bname,
			Integer status, Integer typeid, String bphone, String thingname,String unitida,String startDate,String endDate,String unitidc) {
		resultlist resultMessage = new resultlist();
		try {
			if (page <= 0 || limit <= 0) {
				resultMessage.setMsg("参数错误");
				resultMessage.setCode(1);
			} else {
				PageHelper.startPage(page, limit);
				
				List<thing> things = thingService.selectlistpage(bname, status, typeid, bphone, thingname,startDate,endDate,unitida,unitidc);
				PageInfo<thing> thinginfor = new PageInfo<>(things);
				
				resultMessage.setCount(thinginfor.getTotal());
				resultMessage.setData(thinginfor.getList());
				resultMessage.setCode(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMessage.setMsg(e.getMessage());
			resultMessage.setCode(1);
		}
		return resultMessage;
	}

	@RequestMapping(value = "deletethingthis", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "删除一条事务")
	public ResultMessage deletething(String thingid) {
		ResultMessage resultMessage = new ResultMessage();
		try {
			if (StringUtil.isEmpty(thingid)) {
				resultMessage.setSuccess(false);
				resultMessage.setMessage("参数为空");
			} else {
				thingService.deletethingthis(thingid);
				resultMessage.setSuccess(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMessage.setMessage(e.getMessage());
			resultMessage.setSuccess(false);
		}
		return resultMessage;
	}
}
